package com.jk.garden1.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jk.garden1.dao.*;
import com.jk.garden1.entity.SendcardEntity;
import com.jk.garden1.entity.SubscribeEntity;
import com.jk.garden1.entity.VisitantEntity;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 预约管理表
 */
@Service
@SuppressWarnings("all")
public class SubscribeService {
    @Autowired
    private SubscribeDao subscribeDao;
    @Autowired
    private SubscribeDaos subscribeDaos;
    @Autowired
    private VisitantDaos visitantDaos;
    @Autowired
    private VisitantDao visitantDao;
    @Autowired
    private VisitorDaos visitorDaos;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private ElasticsearchRestTemplate es;
    @Autowired
    private EsSubscribeDao esSubscribeDao;
    /**
     * 查询全部
     */
    public List<SubscribeEntity> selectSubscribeList() {
        QueryWrapper<SubscribeEntity> wrapper = new QueryWrapper<>();
        List<SubscribeEntity> subscribeEntities = subscribeDao.selectList(wrapper);
        for (SubscribeEntity subscribeEntity: subscribeEntities) {
            if(subscribeEntity.getSubscribetime().equals(new Date().toLocaleString())  ){
                VisitantEntity visitantEntity = new VisitantEntity();
                visitantEntity.setVisitantname(subscribeEntity.getVisitantname());
                visitantEntity.setVisitantphone(subscribeEntity.getVisitantphone());
                visitantEntity.setIntervieweename(subscribeEntity.getIntervieweename());
                visitantEntity.setSignintime(subscribeEntity.getSubscribetime());
                visitantEntity.setSignouttime(new Date().toLocaleString());
                visitantEntity.setClassify(subscribeEntity.getSubscribestatus());
                visitantDao.insert(visitantEntity);
            }
        }
        return subscribeEntities;
    }
    /**
     * 删除
     */
    public void delId(Integer subscribeid) {

        subscribeDao.deleteById(subscribeid);
    }
    /**
     * 新增预约
     */
    public void addSubscribe(SubscribeEntity subscribeEntity) {
        subscribeDao.insert(subscribeEntity);
    }
    /**
     *查询即将到访
     */
    public List<SubscribeEntity> findCountList(SubscribeEntity subscribeEntity) {
        QueryWrapper<SubscribeEntity> wrapper = new QueryWrapper<>();
        wrapper.gt("subscribetime",new Date());

        return subscribeDao.selectList(wrapper);

//        String date = new Date().toString();
//         subscribeDaos.findCountList(date);
    }

    public List<VisitantEntity> findClassify(VisitantEntity visitantEntity) {

        return visitantDaos.findClassify(visitantEntity);
    }
    public String sendNote(String[] subscribeids) {
        for (String id : subscribeids) {
//            subscribeDao.deleteById(Integer.parseInt(id));
            System.out.println(id);
            //通过id查询用户信息
            SubscribeEntity subscribeEntity = subscribeDao.selectById(Integer.parseInt(id));
            ObjectMapper objectMapper = new ObjectMapper();
            String msg = null;
            try {
                msg = objectMapper.writeValueAsString(subscribeEntity);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            amqpTemplate.convertAndSend("sendMsgNote",msg);
        }
        return null;
    }

    /**
     * 新建索引
     */
    public void create(){
        es.createIndex(SubscribeEntity.class);
        QueryWrapper wp=new QueryWrapper();
        List<SubscribeEntity> list = subscribeDao.selectList(wp);
        list.forEach(a -> {
            esSubscribeDao.save(a);
        });
    }

    /**
     * es高亮查询
     * @param subscribe
     * @return
     */
    public List<SubscribeEntity> querySubList(SubscribeEntity subscribe) {
        if (es.indexExists(SubscribeEntity.class)){
            create();
        }
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //访客电话精确查
        if(StringUtils.hasText(subscribe.getVisitantphone())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.termQuery("visitantphone",subscribe.getVisitantphone()));
        }
        //被访公司模糊查询
        if(StringUtils.hasText(subscribe.getIntervieweecompany())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("intervieweecompany",subscribe.getIntervieweecompany()));
        }
        //被访人姓名模糊查询
        if(StringUtils.hasText(subscribe.getIntervieweename())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("intervieweename",subscribe.getIntervieweename()));
        }
        //访客姓名模糊查询
        if(StringUtils.hasText(subscribe.getVisitantname())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("visitantname",subscribe.getVisitantname()))
                    .withHighlightFields(new HighlightBuilder.Field("visitantname").preTags("<font color='red'>").postTags("</font>"));
        }
        SearchQuery build = nativeSearchQueryBuilder.build();
        if(StringUtils.hasText(subscribe.getVisitantname())){
            AggregatedPage<SubscribeEntity> employeeEntity = es.queryForPage(build, SubscribeEntity.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    SearchHits hits = searchResponse.getHits();
                    List list = new ArrayList();
                    for (SearchHit hit : hits) {
                        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                        sourceAsMap.put("visitantname", highlightFields.get("visitantname").getFragments()[0].toString());
                        list.add(sourceAsMap);
                    }
                    return new AggregatedPageImpl<>(list);
                }
                @Override
                public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
                    return null;
                }
            });
            return employeeEntity.getContent();
        }else{
            List<SubscribeEntity> list2 = es.queryForList(build, SubscribeEntity.class);
            return  list2;
        }
    }
    /**
     * 查询今日预约人数
     */
    public List<SubscribeEntity> findSubCount() {
        return subscribeDaos.findSubCount();
    }

    public List<SubscribeEntity> findLinShiCount() {
        return subscribeDaos.findLinShiCount();
    }
}
